/* Description: mmap测试
 * Author: zhouhui
 * Release Date: 2014-08-25
 * Modify log: 2014-08-31 
 */ 
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#define FSIZE 30

/*
标准输入修改内存buffer,变更会反应到文件,文件大小为30Byte
参数1: 文件路径
*/
int main(int argc, char **argv)
{
    int fd = open(argv[1], O_RDWR|O_CREAT, 0640);
    if (fd == -1)
    {
        perror("open");
        return 1;
    }

    if (ftruncate(fd, FSIZE) == -1)
    {
        perror("truncate");
        return 1;
    }

    char *buf;
    if ((buf = mmap(NULL,FSIZE,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0)) == MAP_FAILED)
    {
        perror("mmap");
        return 1;
    }
    close(fd);

    int i;
    for(i=0; i<3;i++)
    {
        sleep(5); 
        printf("%d: %s\n", i, buf);

        printf("Change the content of %s:",argv[1]);
        scanf("%30s",buf);
        buf[FSIZE-1] = '\n';
        fflush(stdin);
    }

    char cmd[256]={0};
    sprintf(cmd,"cat %s",argv[1]);
    printf("call system(\"%s\"):\n",cmd);
    system(cmd);
    
    if (munmap(buf, FSIZE) == -1)
    {
        perror("munmap");
        return 1;
    }

    return 0;
}

